package com.yk.system.listener;

import com.yk.common.core.constant.NumberConstant;
import com.yk.common.core.dto.DeviceUpdateDTO;
import com.yk.common.rabbitmq.constant.QueueConstants;
import com.yk.system.entity.Device;
import com.yk.system.entity.OperLog;
import com.yk.system.service.DeviceService;
import com.yk.system.service.OperLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * 设备信息更新监听
 *
 * @author lmx
 * @date 2023/10/21 10:08
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DeviceUpdateListener {

    private final DeviceService deviceService;
    private final OperLogService operLogService;

    @RabbitListener(queues = QueueConstants.DEVICE_UPDATE_STATUS)
    @RabbitHandler
    public void onMessage(DeviceUpdateDTO dto) {
        if (Objects.isNull(dto) || Objects.isNull(dto.getId())) {
            return;
        }
        Device device = deviceService.getById(dto.getId());
        // 状态
        if (Objects.nonNull(device) && Objects.nonNull(dto.getStatus())) {
            boolean status = dto.getStatus().equals(NumberConstant.ONE);
            // 判断当前是上线还是下线
            if (!device.getStatus().equals(status)) {
                deviceOnlineLog(device, status);
                device.setStatus(status);
                deviceService.updateById(device);
            }
        }
    }

    /**
     * 设备上下线日志
     */
    private void deviceOnlineLog(Device device, boolean status) {
        OperLog operLog = new OperLog();
        operLog.setDeviceId(device.getId());
        operLog.setOperName(device.getDeviceName());
        operLog.setStatus(NumberConstant.ZERO);
        operLog.setCreatedAt(new Date());
        operLog.setCreatedBy(1L);
        if (status) {
            operLog.setTitle("设备上线");
            operLog.setBusinessType(NumberConstant.FOUR);
            operLog.setMessage(device.getDeviceName() + "设备上线");
        } else {
            operLog.setTitle("设备下线");
            operLog.setBusinessType(NumberConstant.FIVE);
            operLog.setMessage(device.getDeviceName() + "设备下线");
        }
        operLogService.save(operLog);
    }
}